import 'dart:async';
import 'dart:convert';
import 'package:carbon/json/article_item.dart';
import 'package:dio/dio.dart';
import 'package:crypto/crypto.dart';
import '../json/response_item.dart';
import '../json/user_item.dart';

//code 2开头都是请求成功的，只不过业务上可能不成功
//code 4开头都是请求不成功的。（一般都是 客户端-前端代码问题）
class ArticleApi {
  late Dio _dio;
  String baseUrl = "http://192.168.227.109:8080/CarbonArticleContentController";
  String contents = "";

  ArticleApi() {
    _dio = Dio();
    // 设置contentType
    // _dio.options.headers['Content-Type'] = 'application/x-www-form-unlencoded';
  }

  //注意，在界面调用接口前， 都先检测一下apikey的值。
  Future< ResponseItem< List<ArticleItem?>? > > findTop15Article() async {
    var url =  baseUrl+"/findTop15";
    try {
      Response response = await _dio. get(url);
      // print("userRegister response.data:${response.data}");
      if(response.data.length==0){
        return ResponseItem(code: 404, data: null, message: "找不到文章数据");
      }else{
        List rd = response.data;
        List<ArticleItem> articleItemList = rd.map((e) => ArticleItem.fromJson(e)).toList();
        return ResponseItem<List<ArticleItem>>(code: 200, data: articleItemList, message: "成功查找到文章数据");
      }
    } catch (e) {
      print('userRegister-Error: $e');
      return ResponseItem(code: 400, data: null, message: "客户端代码有问题");
    }
  }



  Future<ResponseItem<ArticleItem?>> userLogin(String accountName, String password,) async {
    var url =  baseUrl+"/findArticleByAccountNameAndPassword";
    Map<String, dynamic> userJson = Map();
    userJson['accountName'] = accountName;
    var bytes = utf8.encode(password);
    userJson['password'] = "${md5.convert(bytes)}";
    // print("${userJson}");
    Response response = await _dio.post(url, data: userJson);
    if(response.data['result']==null){
      // print("用户名或密码错误");
      print("${response.data}");
      return ResponseItem(code: response.data['code'], data: null, message: response.data['message']);
      // return ResponseItem(code: 201, data: null, message: "登录失败，用户名或密码错误");
    }else{
      // print("登陆成功");
      ArticleItem userItem = ArticleItem.fromJson(response.data['result']);
      return ResponseItem<ArticleItem>(code: response.data['code'], data: userItem, message: response.data['message']);
    }
    // try {
    //
    // } catch (e) {
    //   print('userLogin-Error: $e');
    //   return ResponseItem(code: 400, data: null, message: "客户端代码有问题");
    // }
  }
}

void main()async{
  ArticleApi articleApi = ArticleApi();
  var res = await articleApi.findTop15Article();
  // var res = await articleApi.userLogin("小李", "123456");
  //因为可能登录失败，然后返回的data 不是userItem，而是一整个null
  print("${res.data![0]!.content}");
}